package com.wonder.framework.aws.config;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;

import java.net.URI;
import java.net.URISyntaxException;

@Configuration
public class AwsS3Config {
    @Value("${aws-s3.accessKey}")
    private String accessKeyId;

    @Value("${aws-s3.secretKey}")
    private String secretAccessKey;

    @Value("${aws-s3.region}")
    private String region;

    @Value("${aws-s3.endPoint}")
    private String endpointUrl;


    @Bean
    public S3Client s3Client(){
        AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKeyId, secretAccessKey);
        S3Configuration s3Config = S3Configuration.builder().pathStyleAccessEnabled(true).build();
        try{
            S3Client s3 = S3Client.builder()
                    .endpointOverride(new URI(endpointUrl))
                    .credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials))
                    .region(Region.of(region))
                    .serviceConfiguration(s3Config)
                    .build();

            return s3;
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    @Bean
    public S3Presigner s3Presigner(){
        try{
            S3Configuration s3Config = S3Configuration.builder().pathStyleAccessEnabled(true).build();
            S3Presigner presigner = S3Presigner.builder()
                    .endpointOverride(new URI(endpointUrl))
                    .region(Region.of(region))
                    .build();

            return presigner;
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
